<template>
  <div  v-loading.lock="loading" element-loading-text="拼命上传中...">
    <el-upload
      v-if="canDelete"
      ref="upload"
      action="https://upload.qbox.me" 
      :show-file-list="showFileList" 
      :data="dataObj" 
      drag 
      :multiple="basicPackDefault.multiple"
      :before-upload="beforeUpload" 
      :on-success="uploadSuccess"
      :on-change="onChange"
      :auto-upload="true"
      
      :on-error="onError"
      >
      <!-- :accept="basicPack.accept" -->
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <ul  class="el-upload-list el-upload-list--picture" :id="id" >
       <li  v-if="qiniuFile.file_url&&qiniuFile.file_url.length<=0">暂无文件列表</li>
       <template  v-for="(item, index) in qiniuFile.file_url" >
          <li class="el-upload-list__item is-success"  v-if="item != '' " style="width:16%;margin-right:5px;display:inline-block;">
              <img  v-if="(/(.jpg|.JPG|.gif|.GIF|.png|.PNG)$/.test(item))" v-lazy="item"  class="el-upload-list__item-thumbnail"  @click="Viewer($event)" style="cursor:pointer">
              <a class="fileA" v-else :href="item" target="_blank" >
                {{item.substring(item.lastIndexOf("\/") + 1, item.length)}}
              </a>
             <template v-if="canDelete">
               <label  class="el-upload-list__item-status-label">
                       <i class="el-icon-upload-success el-icon-check"></i>
                     </label>
                     <i  class="el-icon-close" @click="delFile(index)"></i>
             </template>
          </li>
        </template>
    </ul>
    
  </div>
</template>
<script>

import { getToken } from '@/api/qiniu'
import store from '@/store'
import qiNiuPrefix from 'config/qiNiuPrefix.js'
import Viewer from "static/viewer/viewer.js"

var timer;
var viewer;
export default{
  mounted(){
    
  },
  props:["qiniuFile",'packJson','canDelete','id'],
  computed: {
    basicPack: {
      get: function () {
        if(this.packJson){
          if(this.packJson.maxLength){
            this.basicPackDefault.maxLength=this.packJson.maxLength;
          }
          if(this.packJson.size){
            this.basicPackDefault.size=this.packJson.size;
          }
          if(this.packJson.accept){
            this.basicPackDefault.accept=this.packJson.accept;

          }
        }
        return this.basicPackDefault
      },
      set: function (v) {
        
      }
    }
  },
  data() { 
    return {
      dataObj: { token: ''},
      showFileList:false,
      basicPackDefault:{
        maxLength:9,   //最大文件数量
        multiple:true, //可否上传多张
        accept:"",
        size:4
      },
      maxLengthPass:"false",
      //进度条参数
      progress:false,
      percentage:0,
      status:"",

      count:0,
      loading:false
      
    }
  },
  methods: {   
    
    delFile(index){
      var fileUrl = this.qiniuFile.file_url;
      if ( fileUrl.length > 0) { 
        fileUrl.splice(index,1);
        this.$refs.upload
        this.$message({
              type: 'success',
              message: '删除成功!'
          });
      }
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    onError(){
      this.loading=false;
      getToken().then(response => { 
        const token = response.uptoken
        store.dispatch('SetQiNiuToken',token)
        _self._data.dataObj.token = token 
        resolve(true)
      }).catch(err => {
        console.log(err)
        reject(false)
      })
      this.$message.error('哎呀,网络君打了下盹，请重新上传!');
    },
    onChange(file, fileList){
      if(file.status=="ready"){
        if(this.qiniuFile.file_url.length+fileList.length>(this.basicPack.maxLength)){//fileList.length+
            this.maxLengthPass=false;
        }else{
            this.maxLengthPass=true;
        }
      }
    },
    beforeUpload(response, file, fileList) {
      this.loading=true;
      if(this.maxLengthPass){
          var isLtM = response.size / 1024 / 1024 < (this.basicPack.size);//文件大小
          if (!isLtM) {
            this.$message.error('上传文件大小不能超过'+(this.basicPack.size)+'MB!');
            this.loading=false;
            return isLtM
          }
          else{
            const _self = this
            return new Promise((resolve, reject) => {
              if(!store.getters.qiNiuToken){
                  getToken().then(response => { 
                    const token = response.uptoken
                    store.dispatch('SetQiNiuToken',token)
                    //commit('SET_QINIUTOKEN', token)
                    _self._data.dataObj.token = token 
                    resolve(true)
                  }).catch(err => {
                    console.log(err)
                    reject(false)
                  })
               }else{
                _self._data.dataObj.token = store.getters.qiNiuToken
                resolve(true)
               }
            })
          }
      }else{
        this.loading=false;
        this.$message.error('最多上传'+(this.basicPack.maxLength)+'个文件!');
        return false
      }
    },
    uploadSuccess(response, file, fileList){
      this.count++;
      this.qiniuFile.file_url.push(qiNiuPrefix+response.key);
      if(this.count==fileList.length){
        this.count=0;
        this.$refs.upload.uploadFiles=[];
      }
      //this.$message.success('上传成功');
      this.$nextTick(()=>{
        if(this.count===0){
          this.loading=false;
        }
      })
    }//图片预览部分的js
    ,Viewer(_this){
      if(_this.currentTarget.getAttribute('lazy')=="error"){
         this.$message.warning('失效的图片链接！')
         return false;
      }
      if($('.viewer-container').length>0){
        var zIndex=document.getElementsByClassName('viewer-container')[0].style['z-index'];
        $('.viewer-close').click();
        viewer=null;
      };
      viewer=new Viewer(document.getElementById(this.id),{  
        fullscreen:false,
        hide: function (){  
          viewer.update();
          viewer.destroy()
          },
          show:function(){
            viewer.update();
          }
        });
      setTimeout(()=>{
        if(zIndex==-1){
          if(document.interchange){
            document.interchange();
          }
        }
      },1000)
    }
  }
}
</script>
<style scoped  >
  @import './../../../static/viewer/viewer.styl';
</style>
<style scoped  >
  .el-upload-list--picture .el-upload-list__item{padding-left:10px!important;}
  .el-upload-list--picture .el-upload-list__item-thumbnail{margin-left: 0;}
  .fileA{cursor: pointer;display: inline-block;width: 70px;height: 70px;word-wrap: break-word;}
</style>
